package com.xxh.springclouddemo.provider.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * sentinel   异常处理
 * @Author xxh
 * @Date 2024/4/22 22:08
 */
@Component
public class DefaultBlockExceptionHandler implements BlockExceptionHandler {


    /**
     * sentinel 限流，降级
     *        限流的异常是： com.alibaba.csp.sentinel.slots.block.flow.FlowException
     *        降级的异常是：com.alibaba.csp.sentinel.slots.block.degrade.DegradeException
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws Exception
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {


        httpServletResponse.setStatus(200);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");

        ObjectMapper objectMapper = new ObjectMapper();

        // 流控
        if (e instanceof FlowException) {
            objectMapper.writeValue(httpServletResponse.getWriter(), "流控");
            // 降级
        } else if (e instanceof DegradeException) {
            objectMapper.writeValue(httpServletResponse.getWriter(), "降级");
            // 未授权
        } else if (e instanceof AuthorityException) {
            objectMapper.writeValue(httpServletResponse.getWriter(), "未授权");
        }




    }
}
